package com.hjs.servlet.user;

import com.hjs.bean.UserInfo;
import com.hjs.bean.Users;
import com.hjs.mapper.UsersMapper;
import com.hjs.tools.Mapper;
import com.hjs.tools.RequestUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author violetfreesia
 * @date 2020/7/3
 */
@Slf4j
@WebServlet("/user/getAllUser")
public class GetUser extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        RequestUtil requestUtil = new RequestUtil(request, response);
        Mapper<UsersMapper> usersMapperMapper = new Mapper<>(UsersMapper.class);
        try {
            UsersMapper mapper = usersMapperMapper.getMapper();
            List<Users> allUser;
            if (requestUtil.getString("id") == null) {
                allUser = mapper.getAllUser();
            } else {
               allUser = mapper.getAllUserByDepartmentId(requestUtil.getInt("id"));
            }
            ArrayList<UserInfo> userInfos = new ArrayList<>();
            allUser.forEach((user)-> userInfos.add(new UserInfo(user)));
            requestUtil.responseWrite(Mapper.toJsonString(userInfos));
        } catch (Exception e) {
            log.error(e.toString());
            requestUtil.responseFail("未知错误");
        } finally {
            usersMapperMapper.closeSession();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    }
}
